/**  定义Content相关的接口 */
const express = require("express");
const router = express.Router();
const Response = require("../utils/Response.js");
// 引入mysql连接池
const pool = require("../utils/db.js");

// 新增社区主题和提问
router.post("/content/add", (req, resp) => {
  let obj = req.body
  let sql = "insert into content set ?"
  pool.query(sql, [obj], (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw error;
    }
    // 成功
    resp.send(Response.ok());
  })
});

// 查询社区主题和提问
router.get("/content/AllList", async (req, resp) => {
  let { page, pagesize } = req.query;
  let startIndex = (page - 1) * pagesize;
  let size = parseInt(pagesize);
  try {
    let sql = "select * from content limit ?,?";
    let result = await pool.querySync(sql, [startIndex, size]);
    let sql2 = "select count(*) as total from content" ;
    let result2 = await pool.querySync(sql2,[]);
    resp.send(
      Response.ok({
        result,
        total: result2[0].total,
        pageIndex: page,
        pageSize: pagesize,
      })
    );
  } catch (error) {
    resp.send(Response.error(error));
  }
});

// 根据科目查询社区主题和提问
router.get("/content/list", async (req, resp) => {
  let { page, pagesize,type } = req.query;
  let startIndex = (page - 1) * pagesize;
  let size = parseInt(pagesize);
  try {
    let sql = "select * from content where content_type=? limit ?,?";
    let result = await pool.querySync(sql, [type,startIndex, size]);
    let sql2 = "select count(*) as total from content where content_type=?" ;
    let result2 = await pool.querySync(sql2,[type]);
    resp.send(
      Response.ok({
        result,
        total: result2[0].total,
        pageIndex: page,
        pageSize: pagesize,
      })
    );
  } catch (error) {
    resp.send(Response.error(error));
  }
});

// 通过社区发布id查找详情数据
router.get("/content/ById", (req, resp) => {
  let {content_id} = req.query
  let sql = "select * from content where content_id=?"
  pool.query(sql, [content_id], (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw error;
    }
    // 成功
    resp.send(Response.ok({result}));
  })
});

// 新增回复
router.post("/content/reply", (req, resp) => {
  let obj = req.body
  let sql = "insert into reply set ?"
  pool.query(sql, [obj], (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw error;
    }
    // 成功
    resp.send(Response.ok());
  })
});

// 通过社区发布id查找回复数据
router.get("/content/replyFid", (req, resp) => {
  let {reply_fid} = req.query
  let sql = "select * from reply where reply_fid=?"
  pool.query(sql, [reply_fid], (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw error;
    }
    // 成功
    resp.send(Response.ok({result}));
  })
});


// 将router对象导出
module.exports = router;